package com.fy.proj5_permission_transaction_cache.service.impl;

import com.fy.proj5_permission_transaction_cache.mapper.RoleMapper;
import com.fy.proj5_permission_transaction_cache.mapper.RolePermissionMapper;
import com.fy.proj5_permission_transaction_cache.mapper.UserRoleMapper;
import com.fy.proj5_permission_transaction_cache.model.Role;
import com.fy.proj5_permission_transaction_cache.model.RolePermission;
import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private CacheService cacheService;

    @Override
    // 暂时移除缓存，确保获取最新数据
    // @Cacheable(value = "roles", key = "'allRoles'")
    public List<Role> findAllRoles() {
        List<Role> roles = roleMapper.findAll();
        // 为每个角色加载权限信息
        for (Role role : roles) {
            Role roleWithPermissions = roleMapper.findRoleWithPermissions(role.getId());
            if (roleWithPermissions != null) {
                role.setPermissions(roleWithPermissions.getPermissions());
            }
        }
        return roles;
    }

    @Override
    @Cacheable(value = "roles", key = "#id")
    public Role findRoleById(Long id) {
        return roleMapper.findById(id);
    }

    @Override
    public Role findRoleByName(String name) {
        return roleMapper.findByName(name);
    }

    // addRole方法已移除

    @Override
    @Transactional
    @Caching(
        put = @CachePut(value = "roles", key = "#role.id"),
        evict = @CacheEvict(value = "roles", key = "'allRoles'")
    )
    public boolean updateRole(Role role) {
        int result = roleMapper.update(role);
        if (result > 0) {
            // 更新缓存
            cacheService.set("role:" + role.getId(), role, 1, TimeUnit.HOURS);
            return true;
        }
        return false;
    }

    // deleteRole方法已移除

    @Override
    // 暂时移除缓存，确保获取最新数据
    // @Cacheable(value = "roles", key = "'roleWithPermissions:' + #roleId")
    public Role findRoleWithPermissions(Long roleId) {
        return roleMapper.findRoleWithPermissions(roleId);
    }

    @Override
    @Transactional
    @CacheEvict(value = {"roles", "permissions"}, allEntries = true)
    public boolean assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        // 先删除该角色原有的权限关联
        rolePermissionMapper.deleteByRoleId(roleId);
        
        // 批量插入新的权限关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (Long permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissions.add(rolePermission);
            }
            rolePermissionMapper.batchInsert(rolePermissions);
        }
        
        // 清除角色缓存
        cacheService.delete("role:" + roleId);
        return true;
    }

    @Override
    @Cacheable(value = "roles", key = "'rolesByUser:' + #userId")
    public List<Role> findRolesByUserId(Long userId) {
        return roleMapper.findRolesByUserId(userId);
    }
}